package com.dong.web;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;

import com.dong.web.whold.Variables;

public final class Redirect {

	private String url = null;

	private String[] exceptions = new String[] { "method" };

	public Redirect(String url) {
		this(url, Variables.ENCODING);
	}

	public Redirect(String url, String encoding) {
		int index = url.indexOf("?");
		if (index != -1) {
			StringBuffer buffer = new StringBuffer("");
			String content = url.substring(index + 1);
			String[] params = content.split("&");
			for (String param : params) {
				if (buffer.length() > 0) {
					buffer.append("&");
				}
				int i = param.indexOf("=");
				String key = param.substring(0, i);
				String value = param.substring(i + 1);
				if (Arrays.asList(exceptions).contains(key)) {
					buffer.append(key).append("=").append(value);
				} else {
					try {
						value = URLEncoder.encode(
								URLEncoder.encode(value, encoding), encoding);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					buffer.append(Variables.START + key).append("=")
							.append(value);
				}
			}
			this.url = url.substring(0, index + 1) + buffer.toString();
		} else {
			this.url = url;
		}
	}

	public String getUrl() {
		return url;
	}

}
